﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Data.Linq;
using System.Text;
using PadnugFramework;
using padnug.Domain;
using PadnugRepositoryInterfaces;


namespace PadnugRepository
{
    public class PadnugProfileRepository : IPadnugProfileRepository
    {
        private padnugEntities db;

        public PadnugProfileRepository()
        {
            db = new padnugEntities();
        }
        #region Implementation of IPadnugProfileRepository

        public PadnugUserProfile FetchProfileData(string userName, string applicationName, bool isAnonymous)
        {
            var dbUser = db.Users.First(p => p.Email.ToLower().CompareTo(userName.ToLower())==0);
            var padnugUserProfile = new PadnugUserProfile()
                                        {
                                            ID = dbUser.ID,
                                            FirstName = dbUser.FirstName,
                                            LastName = dbUser.LastName,
                                            Email = dbUser.Email,
                                        };

            return padnugUserProfile;
        }

        public void SaveProfileData(string userName, string applicationName, bool isAnonymous, PadnugUserProfile padnugUserProfile)
        {
            var dbUser = db.Users.Single(p => p.Email.ToLower().CompareTo(userName.ToLower()) == 0);
            if (dbUser == null) return;
            try
            {
                dbUser.Email = padnugUserProfile.Email;
                dbUser.FirstName = padnugUserProfile.FirstName;
                dbUser.LastName = padnugUserProfile.LastName;
                db.SaveChanges();
            }
            catch (Exception ex)
            {
                throw new ApplicationException(ex.Message);
            }
        }

        #endregion
    }
}
